<?php
class Product_Service_ProductProccess {
	protected $_product = null;
	protected $_productId = null;
	protected $_plan = null;
	protected $_customerId = null;
	protected $_procCnt = 0;
	protected $_products = null;
	protected $_chargeBalance = 0; //扣取费用

	protected $_chargeBalanceCurrency = null;

	protected $_outOfBalance = false;
	protected $_error = null;
	protected $_warning = null;
	protected $_customer = null;
	protected $_logNote = null;
	protected $_unactive = false;

	protected $_status = null;
	protected $_checkOutOfPlan = false;
	protected $_customerPlan = null;
	public function __construct($productId = null) {
		if (isset ($productId)) {
			$this->_productId = $productId;
			$this->setProduct();
			$this->setCustomer();

		}
		$this->_plan = new Plan_Service_Plan();
	}
	/**
	* 用户分发订单
	* @param orderCode
	* @return array|boolean success return boolean,false return array
	*/
	public function submited($status, $productId = null) {
		if (isset ($productId)) {
			$this->_productId = $productId;
			$this->setProduct();
			$this->setCustomer();

		}

		//init Transaction

		$this->_status = $status;
		//		$productService= new Product_Service_Product();
		//		$productModel= new Product_Model_Product();
//		$planService = new Plan_Service_Plan();
		// $dbAdapter = $productModel->getDbTable()->getAdapter();
		// $dbAdapter->beginTransaction();
		switch ($status) {
			case 0 :

				return $this->delete();
				break;
			case 1 : //激活产品

				return $this->active();
				break;
			case 2 : //取消激活

				return $this->unActive();

				break;

		}
		// if(!$this->update()){
		// $dbAdapter->rollback();	
		// return array('product_sku'=>$this->_product['product_sku'],'msg'=>'Internal Error');		
		// }
		// $productService->writeLog(array(),$productId,"1",$this->_product['product_status'],$status);
		// $dbAdapter->commit();
		// return array('product_sku'=>$this->_product['product_sku'],'msg'=>'Success.');	
	}
	/*
	*激活产品
	*
	*/
	private function active() {
		if ($this->_product['product_status'] != 2) {
			// $dbAdapter->rollback();
			return array (
				'product_sku' => $this->_product['product_sku'],
				'msg' => '失败，产品状态必须为草稿.'
			);
		}
		$this->_procCnt = 1;
		$this->_logNote = "Active.";

		$this->checkPlan();
		// if($isCheckPlan & $this->_checkOutOfPlan){				
		// return array('product_sku'=>$this->_product['product_sku'],'msg'=>$this->_error);	
		// }

		//$this->vaildateProduct();
		//if(!empty($this->_error)){			
		//	return array('orders_code'=>$this->_orderCode,'msg'=>implode(",",$this->_error));		
		//}

		$customerBalance = new Customer_Model_CustomerBalance();
		$dbAdapter = $customerBalance->getAdapter();
		$dbAdapter->beginTransaction();
		try {
			$this->dispatch();
			if ($this->_outOfBalance == true) {
				$dbAdapter->rollback();
				$this->update();
				return array (
					'product_sku' => $this->_product['product_sku'],
					'msg' => $this->_error
				);
			}

			$this->update();

			$dbAdapter->commit();
			return array (
				'product_sku' => $this->_product['product_sku'],
				'msg' => "Success"
			);
		} catch (Exception $e) {
			$dbAdapter->rollback();
			return array (
				'product_sku' => $this->_product['product_sku'],
				'msg' => 'Internal Error'
			);
		}

	}
	/*
	*下架已激活产品
	*
	*/
	private function unActive() {
		if ($this->_product['product_status'] != 1) {
			// $dbAdapter->rollback();
			return array (
				'product_sku' => $this->_product['product_sku'],
				'msg' => 'Failure,the product status must be activated'
			);
		}
		$this->_procCnt = -1;
		$this->_logNote = "Unactive.";

		$this->checkUnactive();
		if ($this->_unactive) {
			return array (
				'product_sku' => $this->_product['product_sku'],
				'msg' => $this->_error
			);
		}
		// if($isCheckPlan & $this->_checkOutOfPlan){				
		// return array('product_sku'=>$this->_product['product_sku'],'msg'=>$this->_error,'alert' => true);	
		// }

		$customerBalance = new Customer_Model_CustomerBalance();
		$dbAdapter = $customerBalance->getAdapter();
		$dbAdapter->beginTransaction();
		try {
			$this->dispatch();
			if ($this->_outOfBalance == true) {
				$dbAdapter->rollback();
				$this->update();
				return array (
					'product_sku' => $this->_product['product_sku'],
					'msg' => $this->_error
				);
			}

			$this->update();

			$dbAdapter->commit();
			return array (
				'product_sku' => $this->_product['product_sku'],
				'msg' => "操作成功"
			);
		} catch (Exception $e) {
			$dbAdapter->rollback();
			return array (
				'product_sku' => $this->_product['product_sku'],
				'msg' => '程序内部错误'
			);
		}

	}

	public function delete() {		
		if ($this->_product['product_status'] != 2 || $this->_product['product_warehouse_status'] != 0) {
			// $dbAdapter->rollback();
			return array (
				'product_sku' => $this->_product['product_sku'],
				'msg' => '操作失败，产品必须为草稿或者从来没有被接收！'
			);
		}
		$this->update();
		return array (
			'product_sku' => $this->_product['product_sku'],
			'msg' => "操作成功"
		);
	}

	/*
	*分发 套餐/帐户 扣费处理
	*
	*/
	private function dispatch() { //TODO
		//方法调用 异常？？待确认！！
		$planProc = $this->_plan->planProccessing($this->_customerId, 'sku', $this->_procCnt, "product",$this->_product['product_sku']);
		if ($planProc['ask'] == 'Failure') { //套餐SKU不足

			$meedPayQty = $planProc['data']['qty']; //需要支付数量	
			$holdFee = $this->_plan->getAddtionRate($this->_customerId,'sku', $meedPayQty); //收取费用

			$this->_chargeBalance += $holdFee['value'];
			$this->_chargeBalanceCurrency = $holdFee['currency_code']; //TODO 货币兼容问题待解决
			$options = array (
				'cbhClass' => 0, //正常扣款
				'refCode' => $this->_order['orders_code'],
				'appType' => 4, //item 处理费用
				'cbhType' => '-1',
				'vale' => $holdFee['value'],
				'currencyCode' => $holdFee['currency_code']
			);
			if (Customer_Service_CustomerBalance :: procBalance($this->_customerId, $options)) { //扣款成功
				//记录out of pan 数量				 
				$this->_plan->updatePlanUsage($this->_customerId, 'outofitem', $meedPayQty);
				$this->_warning = $meedPayQty . " Sku out of plan";
				return true;
			} else {
				$this->_outOfBalance = true;
				$this->_error = 'Out of balance, please deposit you Cff account.';
				return false;
			}
		}
		return true;
	}
	/*
	*
	*Check plan
	*/
	private function checkPlan() {
		$this->_customerPlan = $this->_plan->getCurrentPlanUsage($this->_customerId);
		if ($this->_customerPlan->sku_qty + $this->_customerPlan->sku_add_qty - $this->_customerPlan->sku_used - $this->_procCnt < 0) {
			$this->_checkOutOfPlan = true;
		}
		$this->_error = 'Plan available SKU is ' . $this->_customerPlan->item_qty + $this->_customerPlan->sku_add_qty - $this->_customerPlan->item_used . ', this order item picking will out of plan.';
	}

	/*
	*
	*Check unactive
	*/
	private function checkUnactive() { //Todo
		$this->_unactive = false;
		//判断库存
		$wpObj = new Warehouse_Model_Products();

		$warehouseProduct = $wpObj->getByProductId($this->_productId);
		if ($warehouseProduct && !empty ($warehouseProduct)) {
			foreach ($warehouseProduct as $wp) {
				if ($wp['wp_quantity_hold'] > 0 || $wp['wp_quantity'] > 0) {
					$this->_unactive = true;
					$this->_error = "Have available inventory, can not be unactive.";
					break;
				}
			}
		}

		//判断是否存在末发货订单			
		if (!$this->_unactive) {
			$orderObj = new Product_Model_Order();
			$quantity = $orderObj->getByProductId($this->_productId);
			if ($quantity > 0) {
				$this->_unactive = true;
				$this->_error = "有未完成的订单,不能激活";
			}
		}

		//判断是否存在末完成的ASN
		if (!$this->_unactive) {
			$asnObj = new Product_Model_Receiving();
			$condition = array (
				"product_id" => $this->_productId
			);
			$quantity = $asnObj->getByCondition($condition);
			if ($quantity > 0) {
				$this->_unactive = true;
				$this->_error = "有未完成的 asn,不能激活.";
			}
		}

	}

	//TODO validate Product Info//
	private function vaildateProduct() {
		$productObj = new Product_Service_Product();
		$this->_error = $productObj->validate($this->_product);
	}

	/*
	*Update product
	*
	*/

	private function update() {
		$Obj = new Product_Model_Product();
		if ($Obj->changeProductStatus($this->_productId, $this->_status)) {
			$this->writeLog();
			return true;
		}
		return false;
	}
	/*
	*
	*获取客户LOGIN信息
	*
	*/
	private function setCustomer() {		
		$this->_customer = Customer_Service_Customer :: getByCustomerId($this->_product['customer_id']);
		$this->_customerId = $this->_product['customer_id'];

		//		print_r($this->_customer);die();
	}

	private function setProduct() {
		if (!isset ($this->_product) || $this->_product['product_id'] == $this->_productId) {
			$product = Product_Model_Product :: getInstance()->getProduct($this->_productId, $this->_customerId);
			if ($product instanceof Zend_Db_Table_Row) {
				$this->_product = $product->toArray();

			} else {
				$this->_error = '没有权限处理该item!';
				return $this->_error;
			}

		} else {
			$this->_error = '产品id不能为空!';
			return $this->_error;
		}
	}

	public function writeLog() {
		$logRow = array (
			"product_id" => $this->_productId,
			"ph_type" => "1",
			"user_id" => '-1',
			"customer_id" => $this->_customerId,
			"ph_statu_pre" => $this->_product['product_status'],
			"ph_statu_now" => $this->_status,
			"ph_note" => $this->_logNote,
			"ph_add_time" => date('Y-m-d H:i:s'),
			"ph_ip" => $_SERVER['REMOTE_ADDR'],

			
		);
		$dbTable = Product_Model_ProductHistory :: getInstance()->getDbTable();

		$dbTable->insert($logRow);

	}
}